package com.techindata.cacheredis;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author jixiang
 * 
 * 
 *         是否存在与内存中
 * */
public class CacheExsite {
	static Logger logger = Logger.getLogger(CacheExsite.class);
	/**
	 * 
	 * @param key
	 *            存入到cache中
	 * 
	 * @return boolean 是否存在与内存中，存在为true，不存在为false
	 * 
	 * 
	 * **/
	public static boolean isExsite(String key) {

		boolean exsite = false;
		Jedis jedis = null;
		JedisPool pool = RedisConnectionPool.getPool();
		try {
			jedis = pool.getResource();
			exsite = jedis.exists(key);
		} catch (Exception e) {
			// 释放redis对象
			//pool.returnBrokenResource(jedis);
			logger.error(e.getMessage(), e);
		} finally {
			// 返还到连接池
			RedisConnectionPool.returnResource(pool, jedis);
		}
		return exsite;
	}

	/**
	 * 过期
	 * @param str
	 * @param seconds
	 * @return
	 */
	public static long expire(String str, int seconds) {
		long num = 0;
		Jedis jedis=null;
		JedisPool pool = RedisConnectionPool.getPool();
		try {
			jedis= pool.getResource();
			num = jedis.expire(str, seconds);
		} catch (Exception e) {
			if(jedis!=null){
				jedis.disconnect();
			}

			logger.error(e.getMessage(), e);
			new Exception(e.getMessage());
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
		return num;
	}

	/**
	 * 返回过期时间
	 * @param str
	 * @return
	 */
	public static long getExpire(String str) {
		long num = 0;
		Jedis jedis=null;
		JedisPool pool = RedisConnectionPool.getPool();
		try {
			jedis= pool.getResource();
			num = jedis.ttl(str);
		} catch (Exception e) {
			if(jedis!=null){
				jedis.disconnect();
			}

			logger.error(e.getMessage(), e);
			new Exception(e.getMessage());
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
		return num;
	}

	public static void main(String[] args) {
		System.out.println(getExpire("ddr"));
	}
}
